
//  ApplistController.m
//  BuyOfNoWane
//
//  Created by qianfeng02 on 15/7/3.
//  Copyright (c) 2015年 迷茫的尧尧. All rights reserved.
//

#import "ApplistController.h"
#import "AppCell.h"
#import "NewsCell.h"
#import "AppModel.h"
#import "MySelectedController.h"
#import "BuyOverseaController.h"
#import "DisCountController.h"
#import "MMProgressHUD.h"
#import "DetaiController.h"
#import "ILBarButtonItem.h"
#import "SideCategoryController.h"
#import "UIImageView+WebCache.h"
@interface ApplistController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    AFHTTPRequestOperationManager *_manager;
    BOOL _isRefeshing;
    BOOL _isLoadMore;
    UISearchBar *_searchbar;
    UIScrollView *_scrollView;
    UIPageControl *_pageControl;
}
@property (nonatomic)BOOL isRefreshing;
@property (nonatomic)BOOL isLoadMore;
@property(nonatomic ,strong)UITableView *tableView;
@property(nonatomic ,strong)NSMutableArray *dataArray;
@property(nonatomic ,strong)AFHTTPRequestOperationManager *manager;
@property(nonatomic ,strong)NSMutableArray *scrollViewDataArr;
@end

@implementation ApplistController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createTableView];
    _dataArray=[[NSMutableArray alloc]init];
    [self createSidebar];
    
}
#pragma  mark createtableview
-(void)createTableView
{
    if (!_tableView) {
        
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenSize.width, kScreenSize.height-64-49) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.dataSource=self;
        [self.view addSubview:_tableView];
        if ([self.categoryType isEqualToString:kFoundType]) {
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        }
        if ([self.categoryType isEqualToString:kNewsType]) {
            [self.tableView registerNib:[UINib nibWithNibName:@"NewsCell" bundle:nil] forCellReuseIdentifier:@"NewsCell"];
            _tableView.rowHeight=130;
        }else {
        [self.tableView registerNib:[UINib nibWithNibName:@"AppCell" bundle:nil] forCellReuseIdentifier:@"AppCell"];
            _tableView.rowHeight=90;
        }
    }
    self.automaticallyAdjustsScrollViewInsets=NO;
    _manager=[AFHTTPRequestOperationManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
}
#pragma mark -tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AppCell *cell=nil;
    if ([self.categoryType isEqualToString:kNewsType]) {
    cell=[tableView dequeueReusableCellWithIdentifier:@"NewsCell" forIndexPath:indexPath];
    }else{
    cell=[tableView dequeueReusableCellWithIdentifier:@"AppCell" forIndexPath:indexPath];
    }
    AppModel *model=self.dataArray[indexPath.row];
    [cell showDataWithModel:model indexPath:indexPath];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetaiController *detail=[[DetaiController alloc]init];
    AppModel *model=_dataArray[indexPath.row];
    detail.categoryID=model.article_id;
    detail.categoryType=self.categoryType;
    NSLog(@"%@",self.categoryType);
    detail.article_channel_id=model.article_channel_id;
    detail.article_url=model.article_url;
    [self.navigationController pushViewController:detail animated:YES];
}
#pragma mark - 如果不满足子类 那么可以重写
- (void)creatRefreshView
{
//#warning "下拉刷新之后requesturl应该覆写"
    //下拉刷新
    __weak typeof (self)weakSelf=self;
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
        weakSelf.isRefreshing=YES;
        weakSelf.limitNum=20;
        NSString *url=nil;
        url=[NSString stringWithFormat:weakSelf.requestUrl,weakSelf.limitNum];
        [weakSelf addTaskWithUrl:url isRefresh:YES];

    }];
    //上啦加载更多
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isLoadMore) {
            return ;
        }
        weakSelf.isLoadMore=YES;
        weakSelf.limitNum +=20;
        NSString *url=nil;
        url=[NSString stringWithFormat:weakSelf.requestUrl,weakSelf.limitNum];
        [weakSelf addTaskWithUrl:url isRefresh:YES];
    }];
}
- (void)endRefreshing
{
    if (self.isRefreshing) {
        self.isRefreshing = NO;//标记刷新结束
        //正在刷新 就结束刷新
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultNone];
    }
    if (self.isLoadMore) {
        self.isLoadMore = NO;
        [self.tableView footerEndRefreshing];
    }
}
//第一次下载
- (void)firstDownload
{
    
    _limitNum=20;
    NSString *url=[NSString stringWithFormat:_requestUrl,_limitNum];
   
    [self addTaskWithUrl:url isRefresh:NO];
}
//增加下载任务
- (void)addTaskWithUrl:(NSString *)url isRefresh:(BOOL)isRefresh
{
    [MMProgressHUD setPresentationStyle:MMProgressHUDPresentationStyleExpand];
    [MMProgressHUD showWithTitle:@"欢迎光临" status:@"Loading..."];

    __weak typeof (self)weakSelf=self;
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
       // NSLog(@"%@",url);
        if (responseObject) {
            [_dataArray removeAllObjects];
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dict2=dict[@"data"];
            NSArray *rowsarr=dict2[@"rows"];
            for (NSDictionary *dict1 in rowsarr) {
                AppModel *model=[[AppModel alloc]init];
               
                [model setValuesForKeysWithDictionary:dict1];
            
                [weakSelf.dataArray addObject:model];
                if ([model.article_channel_id isEqualToString: @"11"]) {
                    [weakSelf.dataArray removeObject:model];
                }
            }
            [weakSelf.tableView reloadData];
            [weakSelf endRefreshing];
            [MMProgressHUD dismissWithSuccess:@"OK" title:@"数据下载完成"];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"下载失败");
        [MMProgressHUD dismissWithError:nil title:@"网络故障"];
    }];
}
/**
 *  侧边栏
 */
-(void)createSidebar
{
    ILBarButtonItem *sidebtn=[ILBarButtonItem barItemWithImage:[UIImage imageNamed:@"ic_search"] selectedImage:[UIImage imageNamed:@"ic_search"] target:self action:@selector(sidebtnClick:)];
    [self.navigationItem setLeftBarButtonItem:sidebtn];
}
-(void)sidebtnClick:(UIButton *)button
{
    SideCategoryController *sidebar=[[SideCategoryController alloc]init];
    [self.navigationController pushViewController:sidebar animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
